package log.aop;


import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.enums.LoginTypeEnum;
import com.common.exception.MyException;
import com.common.result.Result;
import com.common.result.ResultCode;
import log.constant.LogConstants;
import log.util.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author
 * @Desc
 * @date 2021/6/30 9:27
 */
@Slf4j
@Aspect
@Order(1)
@Component
public class ConsoleLoginAspect extends BaseAspect {
    @Value("${run.type:remote}")
    private String runType;
//    @Resource
//    private LogApi logApi;

    /***/
    @Pointcut("@annotation(log.annotation.LoginLog)")
    public void pointCut() {
    }

    /***/
    @Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        String name = point.getSignature().getName();
        String param = super.getRequestParams(point);
        JSONObject jsonObject = JSONObject.parseObject(param);
        Map<String, Object> innerMap = jsonObject.getInnerMap();
        JSONArray jsonArray = (JSONArray) (innerMap.get("username"));
        String username = jsonArray.get(0).toString();
        String msg = "";
        if ("login".equals(name)) {
            msg = "登录成功";
            try {
                username = RsaUtils.decrypt(username);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("logout".equals(name)) {
            username = null == username ? "" : username;
            msg = "退出成功";
        } else {
            return null;
        }
        super.outputConsoleLogs(point, LogConstants.STOREY_API, LogConstants.IN, param);
        Result result = (Result) point.proceed();
        super.outputConsoleLogs(point, LogConstants.STOREY_API, LogConstants.OUT, null);
        int code = 0;
        if (null != result) {
            if (!ResultCode.SUCCESS.getCode().equals(result.getCode())) {
                code = LogConstants.FAIL;
                msg = result.getMsg();
            }
        }

        if (!LoginTypeEnum.LOCAL.getValue().equals(runType)) {
            saveLog(username, code, msg);
        }

        return result;
    }

    /**
     * 异常-日志记录
     *
     * @param exception
     */
    @AfterThrowing(value = "pointCut()", throwing = "exception")
    public void doAfterThrowingAdvice(JoinPoint point, Throwable exception) {
        String param = super.getRequestParams(point);
        JSONObject jsonObject = JSONObject.parseObject(param);
        String username = jsonObject.get("username").toString();
        try {
            username = RsaUtils.decrypt(username);
        } catch (Exception e) {
        }
        int responseCode = LogConstants.FAIL;
        String mgs = MyException.printToStr(exception);
        if (exception instanceof MyException) {
            MyException e = (MyException) exception;
            if (e.getResultCode() == null) {
                mgs = exception.getMessage();
            } else if (!e.getResultCode().getCode().equals(ResultCode.SYSTEM_ERROR.getCode())) {
                mgs = exception.getMessage();
            }
        } else if (exception instanceof IllegalArgumentException) {
            mgs = exception.getMessage();
        }
        if (!LoginTypeEnum.LOCAL.getValue().equals(runType)) {
            saveLog(username, responseCode, mgs);
        }
    }

    private void saveLog(String userName, int code, String exMsg) {
        //获取登录ip
        //获取请求头的User-Agent，拿到登录浏览器、登录系统
        String userAgentStr = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
//        SysLogLoginDTO sysLogLoginDTO = new SysLogLoginDTO();
//        sysLogLoginDTO.setUserName(userName);
//        sysLogLoginDTO.setLoginIp(request.getRemoteAddr());
//        sysLogLoginDTO.setLoginBrowser(userAgent.getBrowser().getName());
//        sysLogLoginDTO.setLoginSystem(userAgent.getPlatform().getName());
//        sysLogLoginDTO.setLoginStatus(code);
//        sysLogLoginDTO.setLoginMsg(exMsg);
//        sysLogLoginDTO.setLoginTime(new Date());
//        logApi.addLogin(sysLogLoginDTO);
    }

}
